/*================================================================
 *   Copyright (C) 2021 All rights reserved.
 *   
 *   文件名称：thread.h
 *   创 建 者：汉森伯逸
 *   创建日期：2021年04月26日
 *   描    述：
 *
 *================================================================*/
#pragma once

#include <thread>
#include <atomic>
#include <memory>
#include <functional>
#include <cstdint>
#include <pthread.h>
#include <semaphore.h>
#include "util/noncopyable.h"
#include "util/dump.h"
#include "mutex.h"

namespace hsby{

/*
 * @biref 线程上下文
 */
class Thread : Noncopyable, public BaseDump{
public:
    typedef std::shared_ptr<Thread> Ptr;

public:
    Thread(std::function<void()>, const std::string& name = "none");
    ~Thread();

public:
    void Dump(std::ostream &os) const override;

private:
    /*
     * @biref 禁止默认拷贝和赋值
     */
    Thread(const Thread& ) = delete;
    Thread(const Thread&& ) = delete;
    Thread& operator=(const Thread& ) = delete;

    /*
     * @biref 线程正文(在正文中执行上下文的cb)
     */
    static void* Run(void* args);

public:
    static Thread* GetThread();
    static void SetThread(Thread *);
    static const std::string& GetThreadName();
    static void SetThreadName(const std::string& );

public:
    /*
     * @biref 操作线程上下文中的name、id
     */
    const std::string& GetName() const {return name_;}
    const pid_t GetId() const { return id_;}

    /*
     * @biref 回收线程
     */
    void join();

private:
    pid_t       id_ = -1;
    std::string name_;
    pthread_t   thread_ = 0;
    std::function<void()> cb_;

    Semaphore semaphore_; /* 信号量, 保证线程初始化完成返回时已经被执行 */
};

}// namespace hsby